#include "Thread.hpp"
using namespace kp;

int g_tickets = 10000;
const int threadnum = 4;

void route(kp::threaddata *&td)
{
  while (true)
  {
    kp::LookGuard grard(&td->_mutex);
    if (td->_tickets > 0)
    {
      usleep(100);
      printf("%s is running get tickets: %d\n", td->_name.c_str(), td->_tickets);
      td->_tickets--;
      td->_total++;
    }
    else
    {
      break;
    }
  }
}

int main()
{

  std::vector<Thread<threaddata *>> threads;
  std::vector<threaddata *> datas;

  pthread_mutex_t mutex;
  int i = pthread_mutex_init(&mutex, nullptr);
  if (i != 0)
  {
    std::cerr << "Mutex init failed" << std::endl;
    return 1;
  }
  for (int i = 0; i < threadnum; i++)
  {
    std::string name = "thread-" + std::to_string(i + 1);
    threaddata *td = new threaddata(name, g_tickets, mutex);
    threads.emplace_back(name, td, route);
    datas.emplace_back(td);
  }

  for (auto &thread : threads)
  {
    thread.start();
  }

  for (auto &thread : threads)
  {
    thread.join();
    std::cout << "wait thread done, thread is: " << thread.name() << std::endl;
  }
    for (auto &thread : datas)
  {
    std::cout << "wait thread done, thread tickets: " << thread->_total << std::endl;
  }


  return 0;
}
